from sklearn import datasets
import tensorflow as tf
import pandas as pd


def build_net():
    # 输入是2个特征的所以我们使用[None, 2]
    inputs = tf.placeholder(tf.float32, [None, 2])
    labels = tf.placeholder(tf.float32, [None, 1])
    # 我们的感知器的参w1和w2
    weights = tf.Variable(tf.random_uniform([2, 1]))
    # 感知器的偏置值
    bias = tf.Variable(tf.zeros([1, 1]))
    # 加权相加后通过激活函数得到输出
    outs = tf.sigmoid(tf.matmul(inputs, weights) + bias)
    # 根据输出和label的区别来确定loss
    loss = tf.reduce_mean(tf.square(outs - labels))
    # 使用梯度下降来优化loss
    optimizer = tf.train.\
        GradientDescentOptimizer(0.1).minimize(loss)

    return inputs, labels, optimizer, outs


def main():
    # 获取iris的数据
    iris_data = datasets.load_iris()
    # 将iris的数据变成一个DataFrame
    iris = pd.DataFrame(iris_data.data, 
                        columns=iris_data.feature_names)
    iris['target'] = iris_data.target
    # 在这里选取花萼长度和花瓣长度作为输入iris_x, 花的种类作为输出iris_y
    iris_x = iris[['sepal length (cm)', 'petal length (cm)']].values
    iris_y = iris['target'].values
    # iris数据集里面一共有3种花，每种50个，
    # 由于iris的种类是按照顺序的0-50是第一种，
    # 50-100是第二种，这里我们使用二分类所以只选取了前100笔数据。
    x = iris_x[:100]
    y = iris_y[:100].reshape(-1, 1)
    print(x.shape, y.shape)
    # 构建神经网络
    inputs, labels, optimizer, outs = build_net()
    with tf.Session() as sess:
        # 初始化参数
        sess.run(tf.global_variables_initializer())
        for epoch in range(200):
            # 训练神经网络
            _, out = sess.run([optimizer, outs],
                              feed_dict={inputs: x, labels: y})
            # 打印训练的次数，神经网络的输出，真实的label
            print('Epoch :', epoch, out, y)


if __name__ == '__main__':
    main()
